package net.csdn.business.mirror.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.PageDto;
import net.csdn.business.common.domain.mirror.*;
import net.csdn.business.common.domain.query.mirror.MirrorConfigQuery;
import net.csdn.business.common.domain.query.mirror.MirrorPageQuery;
import net.csdn.business.common.domain.query.mirror.TokenConfigQuery;
import net.csdn.business.common.domain.request.mirror.*;
import net.csdn.business.common.domain.vo.mirror.*;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.exception.BusinessException;
import net.csdn.business.common.service.SuperServiceImpl;
import net.csdn.business.mirror.SpringBeanUtil;
import net.csdn.business.mirror.common.Constants;
import net.csdn.business.mirror.config.ImportMirrorConfig;
import net.csdn.business.mirror.entity.bean.ProjectMirrorData;
import net.csdn.business.mirror.entity.bean.UserGithubToken;
import net.csdn.business.mirror.entity.bo.github.UserBO;
import net.csdn.business.mirror.enums.ProjectMirrorEnum;
import net.csdn.business.mirror.enums.UserTokenEnum;
import net.csdn.business.mirror.mapper.ProjectMirrorDataMapper;
import net.csdn.business.mirror.service.ImportMirrorService;
import net.csdn.business.mirror.service.ProjectMirrorDataService;
import net.csdn.business.mirror.service.UserGithubTokenService;
import net.csdn.business.mirror.utils.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProjectMirrorDataServiceImpl extends SuperServiceImpl<ProjectMirrorDataMapper, ProjectMirrorData> implements ProjectMirrorDataService {

    @Autowired
    private ImportMirrorConfig importMirrorConfig;
    @Autowired
    private ImportMirrorService importMirrorService;
    @Autowired
    @Lazy
    private UserGithubTokenService userGithubTokenService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public ProjectMirrorData getById(Long id) {
        if (Objects.isNull(id) || id < 1) {
            return null;
        }
        return baseMapper.selectById(id);
    }

    @Override
    public ProjectMirrorData getByFullPath(String fullPath) {
        if (StringUtils.isEmpty(fullPath)) {
            return null;
        }
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getFullPath, fullPath);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<ProjectMirrorData> getByFullPaths(List<String> fullPaths) {
        if (CollectionUtils.isEmpty(fullPaths)) {
            return null;
        }
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.in(ProjectMirrorData::getFullPath, fullPaths);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public void updateAllStatus(ProjectMirrorData data, Integer status) {
        if (Objects.isNull(data) || Objects.isNull(data.getId()) || status < 0) {
            return;
        }
        ProjectMirrorData d = ProjectMirrorData.builder()
                .id(data.getId())
                .status(status)
                .syncStatus(status)
                .build();
        baseMapper.updateById(d);
    }

    @Override
    public void updateAllStatus(Long id, Integer status) {
        ProjectMirrorData d = ProjectMirrorData.builder()
                .id(id)
                .status(status)
                .syncStatus(status)
                .build();
        baseMapper.updateById(d);
    }

    @Override
    public Integer deleteMirror(MirrorDelDTO params) throws Exception {
        Long id=params.getId();
        ProjectMirrorData projectMirrorData=baseMapper.selectById(id);
        if(projectMirrorData==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        int res=baseMapper.deleteById(id);
        //删除队列中已存在的此值
        try {
            stringRedisTemplate.opsForList().remove(Constants.MIRROR_IMPORT_KEY, Integer.MAX_VALUE, id);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("redis remove  task queue error, key: {}, value: {}", Constants.MIRROR_IMPORT_KEY, id, e);
        }
        return res;
    }

    @Override
    public void retry(MirrorRetyDTO params) throws Exception{
        Long id=params.getId();
        ProjectMirrorData projectMirrorData=baseMapper.selectById(id);
        if(projectMirrorData==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        importMirrorService.push(projectMirrorData.getId(), true);
    }

    @Override
    public PageDto<ProjectMirrorData> searchData(ProjectMirrorDataQueryDto dto) {
        Page<ProjectMirrorData> page = listPage(dto);
        return PageDto.build(page.getRecords(), ((int) page.getCurrent()), ((int) page.getSize()), page.getTotal());
    }

    @Override
    public Page<ProjectMirrorDataVO> listPageMirror(MirrorPageQuery query) {
        Page<ProjectMirrorDataVO> page=query.getPage();
        List<ProjectMirrorDataVO> list=baseMapper.findPageList(page,query);
        if(list!=null&&list.size()>0){
            for (ProjectMirrorDataVO data : list) {
                UserTokenEnum.Type t = UserTokenEnum.Type.parse(data.getType());
                data.setTypeDesc(t.getName());
                StringBuilder sourceUrl = new StringBuilder(t.getBaseUrl());
                sourceUrl.append(data.getRepoPath());
                data.setSourceUrl(sourceUrl.toString());
                data.setStatusDesc(ProjectMirrorEnum.Status.TRANS_MAP.getOrDefault(data.getStatus(), ""));
                StringBuilder targetUrl = new StringBuilder(importMirrorConfig.getMirrorUrl());
                targetUrl.append(data.getFullPath());
                data.setTargetUrl(targetUrl.toString());
            }
        }
        page.setRecords(list);
        return page;
    }

    private Page<ProjectMirrorData> listPage(ProjectMirrorDataQueryDto dto) {
        QueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>();
        LambdaQueryWrapper<ProjectMirrorData> lambdaQueryWrapper = queryWrapper.lambda();
        if (StringUtils.isNotEmpty(dto.getStatusStr())) {
            List<Integer> statusList = Arrays.stream(dto.getStatusStr().split(",")).map(Integer::new).collect(Collectors.toList());
            lambdaQueryWrapper.in(ProjectMirrorData::getStatus, statusList);
        } else if (Objects.nonNull(dto.getStatus())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getSyncStatusStr())) {
            List<Integer> statusList = Arrays.stream(dto.getSyncStatusStr().split(",")).map(Integer::new).collect(Collectors.toList());
            lambdaQueryWrapper.in(ProjectMirrorData::getSyncStatus, statusList);
        } else if (Objects.nonNull(dto.getSyncStatus())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getSyncStatus, dto.getSyncStatus());
        }
        if (StringUtils.isNotEmpty(dto.getRepoPath())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getRepoPath, dto.getRepoPath());
        }
        if (StringUtils.isNotEmpty(dto.getFullPath())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getFullPath, dto.getFullPath());
        }
        if (Objects.nonNull(dto.getProjectId())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getProjectId, dto.getProjectId());
        }
        if (Objects.nonNull(dto.getNextExecutionAt())) {
            lambdaQueryWrapper.lt(ProjectMirrorData::getNextExecutionAt, dto.getNextExecutionAt());
        }
        if (Objects.nonNull(dto.getNextSyncExecutionAt())) {
            lambdaQueryWrapper.lt(ProjectMirrorData::getNextSyncExecutionAt, dto.getNextSyncExecutionAt());
        }
        if (Objects.nonNull(dto.getNextMinId())) {
            lambdaQueryWrapper.gt(ProjectMirrorData::getId, dto.getNextMinId());
        }
        if (Objects.nonNull(dto.getUserType())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getUserType, dto.getUserType());
        }
        if (StringUtils.isNotEmpty(dto.getCreateStartDate())) {
            Date _t = TimeUtil.getTime(dto.getCreateStartDate(), TimeUtil.DEFAULT_FORMAT);
            lambdaQueryWrapper.gt(ProjectMirrorData::getCreatedAt, _t);
        }
        if (StringUtils.isNotEmpty(dto.getCreateEndDate())) {
            Date _t = TimeUtil.getTime(dto.getCreateEndDate(), TimeUtil.DEFAULT_FORMAT);
            lambdaQueryWrapper.lt(ProjectMirrorData::getCreatedAt, _t);
        }

        boolean skipType = false;
        if (StringUtils.isNotEmpty(dto.getMirrorUrl())) {
            UserTokenEnum.Type t = UserTokenEnum.Type.parseUrl(dto.getMirrorUrl());
            if (Objects.nonNull(t)) {
                String[] arr = dto.getMirrorUrl().split(t.getBaseUrl());
                if (arr.length == 2 && StringUtils.isNotEmpty(arr[1])) {
                    lambdaQueryWrapper.eq(ProjectMirrorData::getType, t.getCode());
                    lambdaQueryWrapper.like(ProjectMirrorData::getRepoPath, arr[1]);
                    skipType = true;
                }
            } else {
                lambdaQueryWrapper.like(ProjectMirrorData::getRepoPath, dto.getMirrorUrl());
            }
        }
        if (!skipType && Objects.nonNull(dto.getType())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getType, dto.getType());
        }
        if (Objects.nonNull(dto.getIsSync())) {
            lambdaQueryWrapper.eq(ProjectMirrorData::getIsSync, dto.getIsSync());
        }
        if (Objects.nonNull(dto.getOrder())) {
            queryWrapper.orderBy(true, dto.getOrder().isAsc(), dto.getOrder().getName());
        } else {
            queryWrapper.orderBy(true, false, "id");
        }
        Page<ProjectMirrorData> page = new Page<>(dto.getPageNum(), dto.getPageSize(), dto.isSearchCount());
        baseMapper.selectPage(page, lambdaQueryWrapper);
        return page;
    }

    @Override
    public void updateMirrorData(Long id, Integer status,Date nextExecutionAt,Date lastExecutionAt, String error) {
        ProjectMirrorData data = ProjectMirrorData.builder()
                .id(id)
                .status(status)
                .build();
        if (Objects.nonNull(nextExecutionAt)) {
            data.setNextExecutionAt(nextExecutionAt);
        }
        if (Objects.nonNull(lastExecutionAt)) {
            data.setLastExecutionAt(lastExecutionAt);
        }
        if (StringUtils.isNotEmpty(error)) {
            data.setLastError(error);
        }
        baseMapper.updateById(data);
    }

    @Override
    public void updateSyncMirrorData(Long id, Integer status, Date nextExecutionAt, String error) {
        ProjectMirrorData data = ProjectMirrorData.builder()
                .id(id)
                .syncStatus(status)
                .nextSyncExecutionAt(nextExecutionAt)
                .build();

        if (status == 3) {
            data.setLastSyncSuccessfulUpdateAt(new Date());
        } else if (StringUtils.isNotEmpty(error)) {
            data.setLastSyncError(error);
        }
        baseMapper.updateById(data);
    }

    @Override
    public void batchInsert(AddMirrorImportDataDTO dto) {
        int userType = dto.isSkipBlack() ? 1 : 0;
        batchInsert(dto.getCreator(), dto.getUserId(), dto.getToken(), userType, dto.getType(),dto.getIsSync(), dto.getImports());
    }

    @Override
    public void batchInsert(String creator, String creatorId, String token, int userType, int type,int isSync,List<AddMirrorImportDataDTO.Info> imports) {
        baseMapper.batchImportInsert(creator, creatorId, token, userType, type,isSync, imports);
        List<String> fullPaths = imports.stream().map(AddMirrorImportDataDTO.Info::getFullPath).collect(Collectors.toList());
        List<ProjectMirrorData> data = getByFullPaths(fullPaths);
        importMirrorService.push(data.stream().map(ProjectMirrorData::getId).collect(Collectors.toList()));
    }

    @Override
    public void startImport(AddMirrorImportDataDTO dto) {
        if (CollectionUtils.isEmpty(dto.getImports())) {
            return;
        }
        if (StringUtils.isBlank(dto.getToken())) {
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM, "token");
        }
        UserTokenEnum.Type t = UserTokenEnum.Type.parse(dto.getType());
        UserBO user = SpringBeanUtil.getBean(t.getThirdApiService()).getUser(dto.getToken());
        if (Objects.isNull(user)) {
            throw new BusinessException(ResultCodeEnum.MIRROR_GITHUB_TOKEN_INVALID);
        }
        for (AddMirrorImportDataDTO.Info info : dto.getImports()) {
            if (StringUtils.isEmpty(info.getRepoPath()) || info.getRepoPath().split("/").length != 2 ||
                    StringUtils.isEmpty(info.getFullPath()) || info.getFullPath().split("/").length != 2) {
                throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM, "repoPath");
            }
            if (StringUtils.isAnyBlank(info.getOrgId(), info.getOrgName())) {
                throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR);
            }
        }
        int userType = dto.isSkipBlack() ? 1 : 0;
        batchInsert(dto.getCreator(), dto.getUserId(), dto.getToken(), userType, dto.getType(),dto.getIsSync(), dto.getImports());
        //20240717去掉下面缓存逻辑，上面都放到队列里了，队列消费去查询缓存，会出现不存在的情况，所以下面逻辑多余
        //importMirrorService.cacheMirrorInfo(dto.getImports());
    }

    @Override
    public long mirrorImportSize() {
        QueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>();
        LambdaQueryWrapper<ProjectMirrorData> lambdaQueryWrapper = queryWrapper.lambda();
        lambdaQueryWrapper.eq(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._0.code);
        //lambdaQueryWrapper.eq(ProjectMirrorData::getUserType, ProjectMirrorEnum.UserType._0.code);
        return baseMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public void importSuccess(ProjectMirrorData data, Long projectId) {
        if (Objects.isNull(data) || Objects.isNull(projectId)) {
            return;
        }
        if (!data.getStatus().equals(ProjectMirrorEnum.Status._0.code)) {
            return;
        }
        ProjectMirrorData mirrorData = ProjectMirrorData.builder()
                .status(ProjectMirrorEnum.Status._1.code)
                .syncStatus(ProjectMirrorEnum.Status._1.code)
                .projectId(projectId)
                .build();
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getId, data.getId());
        queryWrapper.eq(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._0.code);
        baseMapper.update(mirrorData, queryWrapper);
    }

    @Override
    public void importFailed(ProjectMirrorData data, Long projectId) {
        if (Objects.isNull(data) || Objects.isNull(projectId)) {
            return;
        }
        if (!data.getStatus().equals(ProjectMirrorEnum.Status._0.code)) {
            return;
        }
        ProjectMirrorData mirrorData = ProjectMirrorData.builder()
                .projectId(projectId)
                .id(data.getId())
                .status(ProjectMirrorEnum.Status._7.code)
                .syncStatus(ProjectMirrorEnum.Status._7.code)
                .build();
        baseMapper.updateById(mirrorData);
    }

    @Override
    public void mirrorSuccess(ProjectMirrorData data) {
        if (Objects.isNull(data)) {
            return;
        }
        if (!data.getStatus().equals(ProjectMirrorEnum.Status._2.code)) {
            return;
        }
        ProjectMirrorData mirrorData = ProjectMirrorData.builder()
                .status(ProjectMirrorEnum.Status._3.code)
                .lastExecutionAt(new Date())
                .build();
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getId, data.getId());
        queryWrapper.eq(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._2.code);
        baseMapper.update(mirrorData, queryWrapper);
    }

    @Override
    public void mirrorFailed(ProjectMirrorData data) {
        if (Objects.isNull(data)) {
            return;
        }
        if (!data.getStatus().equals(ProjectMirrorEnum.Status._2.code)) {
            return;
        }
        ProjectMirrorData mirrorData = ProjectMirrorData.builder()
                .status(ProjectMirrorEnum.Status._4.code)
                .build();
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getId, data.getId());
        queryWrapper.eq(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._2.code);
        baseMapper.update(mirrorData, queryWrapper);
    }


    @Override
    public Map<String, ProjectMirrorData> getByCreatorAndRepoPaths(String creatorId, List<String> fullPaths) {
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getCreatorId, creatorId);
        queryWrapper.in(ProjectMirrorData::getRepoPath, fullPaths);
        List<ProjectMirrorData> data = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(data)) {
            return new HashMap<>();
        }
        Map<String, ProjectMirrorData> result = new HashMap<>();
        for (ProjectMirrorData d : data) {
            result.put(d.getRepoPath(), d);
        }
        return result;
    }


    public Map<String, ProjectMirrorData> getMirrorByRepoPaths(Integer type,String creatorId,List<String> fullPaths){
        return baseMapper.selectMirrorDataMap(type,creatorId,fullPaths);
    }

    @Override
    public Integer delete(ProjectMirrorData data) {
        if (Objects.isNull(data)) {
            return null;
        }
        return baseMapper.deleteById(data.getId());
    }


    @Override
    public MirrorConfigVO getTokenConfig(TokenConfigQuery query) {
        String userId=query.getUserId();
        if(StringUtils.isBlank(userId)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"userId");
        }
        Integer type=query.getType();
        MirrorConfigVO result=null;
        //根据用户id和平台类型查询token信息
        UserGithubToken userGithubToken=userGithubTokenService.getToken(userId,type);
        if(userGithubToken!=null){
            result=new MirrorConfigVO();
            result.setType(userGithubToken.getType());
            result.setToken(userGithubToken.getData());
            result.setStatus(userGithubToken.getStatus());
            result.setThirdUsername(userGithubToken.getThirdUsername());
        }
        return result;
    }


    @Override
    public MirrorConfigVO getConfig(MirrorConfigQuery query) {
        //String userId=query.getUserId();
        //查询镜像仓库信息
        MirrorConfigVO result=null;
        Long projectId=query.getProjectId();
        if(projectId==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"projectId");
        }
        /*ProjectVo projectVo=projectFeignClient.getProjectById(projectId);
        if(projectVo==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"projectId");
        }
        String fullPath=projectVo.getPathWithNamespace();*/
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getProjectId, projectId);
        ProjectMirrorData projectMirrorData=baseMapper.selectOne(queryWrapper);
        if(projectMirrorData!=null){
            result=new MirrorConfigVO();
            ProjectMirrorVO mirror=new ProjectMirrorVO();
            BeanUtils.copyProperties(projectMirrorData,mirror);
            result.setMirror(mirror);
            Integer type=projectMirrorData.getType();
            String userId=projectMirrorData.getCreatorId();
            //根据用户id和平台类型查询token信息
            UserGithubToken userGithubToken=userGithubTokenService.getToken(userId,type);
            if(userGithubToken!=null){
                result.setType(userGithubToken.getType());
                result.setToken(userGithubToken.getData());
                result.setThirdUsername(userGithubToken.getThirdUsername());
            }
        }
        return result;
    }

    @Override
    public void updateTokenConfig(TokenConfigDTO params) throws Exception {
        String token=params.getToken();
        Integer type=params.getType();
        String userId=params.getUserId();
        if(StringUtils.isBlank(userId)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"userId");
        }
        //String userName =nameSpaceFeignClient.targetIdToPath(userId);
        String userName="";
        if(StringUtils.isBlank(userName)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"userId");
        }
        UserTokenEnum.Type t = UserTokenEnum.Type.parse(type);
        //首先验证token是否有效
        UserBO user = SpringBeanUtil.getBean(t.getThirdApiService()).getUser(token);
        if (Objects.isNull(user)) {
            throw new BusinessException(ResultCodeEnum.MIRROR_GITHUB_TOKEN_INVALID);
        }
        //保存token
        MirrorUserTokenDTO userTokenParams=new MirrorUserTokenDTO();
        userTokenParams.setUserId(userId);
        userTokenParams.setType(type);
        userTokenParams.setToken(token);
        userTokenParams.setThirdUsername(user.getLogin());
        userTokenParams.setUsername(userName);
        userGithubTokenService.addOrUpdate(userTokenParams);
        //异步更新相关导入项目的token
        /*taskExecutor.execute(()->{
            //批量更新此人导入的仓库中保存的token信息
            //更新镜像仓库的同步开关
            LambdaUpdateWrapper<ProjectMirrorData> updateWrapper = new UpdateWrapper<ProjectMirrorData>().lambda();
            updateWrapper.eq(ProjectMirrorData::getCreatorId, userId);
            updateWrapper.eq(ProjectMirrorData::getType, type);
            updateWrapper.set(ProjectMirrorData::getToken, token);
            int result=baseMapper.update(null,updateWrapper);
            log.info("------更新token结果：{}",result);
        });*/
    }


    /** 
    * @Description: 用户配置镜像仓库
    * @Param: 
    * @return: 
    * @Author: zhangyl
    * @Date: 2024/7/18
    */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConfig(MirroConfigDTO params) throws Exception {
        String token=params.getToken();
        String currUserId=params.getCurrUserId();
        Long projectId=params.getProjectId();
        Integer isSync=params.getIsSync();
        //检查是否已存在该仓库的镜像配置
        LambdaQueryWrapper<ProjectMirrorData> queryWrapper = new QueryWrapper<ProjectMirrorData>().lambda();
        queryWrapper.eq(ProjectMirrorData::getProjectId, projectId);
        ProjectMirrorData projectMirrorData=baseMapper.selectOne(queryWrapper);
        if(projectMirrorData==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"projectId");
        }
        Long id=projectMirrorData.getId();
        //验证当前用户权限
        /*if(!projectFeignClient.checkProjectPermission(currUserId,projectId, ProjectEnum.AccessLevelEnum.MANAGER.getCode())){
            throw new BusinessException(ResultCodeEnum.MIRROR_CONFIG_FORBID);
        }*/
        //更新开关
        //更新镜像仓库的同步开关
        LambdaUpdateWrapper<ProjectMirrorData> updateWrapper = new UpdateWrapper<ProjectMirrorData>().lambda();
        updateWrapper.eq(ProjectMirrorData::getProjectId, projectId);
        updateWrapper.set(ProjectMirrorData::getIsSync, isSync);
        if(StringUtils.isNotBlank(token)){
            updateWrapper.set(ProjectMirrorData::getToken, token);
        }
        /*if (projectMirrorData.getProjectId()!=null) {
            updateWrapper.set(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._1.code);
            updateWrapper.set(ProjectMirrorData::getSyncStatus, ProjectMirrorEnum.Status._1.code);
        } else {
            updateWrapper.set(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._0.code);
            updateWrapper.set(ProjectMirrorData::getSyncStatus, ProjectMirrorEnum.Status._0.code);
        }*/
        int result=baseMapper.update(null,updateWrapper);
        //开启的时候，需要加入队列,立即进行同步或者导入
        if(result>0&&isSync==1){
            importMirrorService.push(id);
        }
        //更新token逻辑
        if(StringUtils.isNotBlank(token)){
            String sourcePath=projectMirrorData.getRepoPath();
            Integer type=projectMirrorData.getType();
            UserTokenEnum.Type t = UserTokenEnum.Type.parse(type);
            //调用api查询源仓库是否有效
            MyGithubDto.Repository repository = SpringBeanUtil.getBean(t.getThirdApiService()).userRepo(token,sourcePath);
            if(repository==null){
                throw new BusinessException(ResultCodeEnum.MIRROR_GITHUB_TOKEN_INVALID);
            }
            TokenConfigDTO tokenParams=new TokenConfigDTO();
            tokenParams.setUserId(currUserId);
            tokenParams.setType(type);
            tokenParams.setToken(token);
            this.updateTokenConfig(tokenParams);
        }
    }

    @Override
    public MirrorProjectPageVO getRepoList(MirrorConfigQuery params)  throws Exception{
        Integer type=params.getType();
        String currUserId=params.getCurrUserId();
        String targetNameSpace=params.getTargetNameSpace();
        if(StringUtils.isBlank(targetNameSpace)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"targetNameSpace");
        }
        //根据查询条件查询用户token信息
        UserGithubToken userGithubToken=userGithubTokenService.getValidToken(currUserId,type);
        if(userGithubToken==null){
            throw new BusinessException(ResultCodeEnum.MIRROR_GITHUB_TOKEN_INVALID);
        }
        String token=userGithubToken.getData();
        String thirdUserName = userGithubToken.getThirdUsername();
        UserTokenEnum.Type t = UserTokenEnum.Type.parse(type);
        //根据用户选择的平台类型，查询镜像仓库列表
        ListRepoDTO repoDTO=new ListRepoDTO();
        repoDTO.setToken(token);
        repoDTO.setThirdUserName(thirdUserName);
        repoDTO.setNamespace(params.getSoruceNameSpace());
        repoDTO.setPage(params.getPage());
        repoDTO.setPageSize(params.getPageSize());
        MirrorProjectPageVO result = SpringBeanUtil.getBean(t.getThirdApiService()).getALlRepos(repoDTO);
        if(result!=null){
            Map<String, ProjectMirrorData> importDateMap =null;
            List<MirrorRepositoryVO> repos = result.getItems();
            if(repos!=null&&repos.size()>0){
                List<String> targetPathList = new ArrayList<String>();
                List<String> fullPaths = repos.stream().map(MirrorRepositoryVO::getFullName).collect(Collectors.toList());
                importDateMap = this.getMirrorByRepoPaths(type,currUserId, fullPaths);
                Integer importCount=0;
                if(importDateMap!=null&&importDateMap.size()>0){
                    for (MirrorRepositoryVO repo : repos) {
                        ProjectMirrorData data = importDateMap.get(repo.getFullName());
                        if(data!=null){
                            importCount += 1;
                            repo.setImportedId(data.getId().toString());
                            repo.setImported(true);
                            repo.setTargetPath(data.getFullPath());
                            repo.setImportedUrl(importMirrorConfig.getMirrorUrl() + data.getFullPath());
                            String importedDesc = null;
                            Integer importedStatus=-1;
                            //Long projectId=data.getProjectId();
                            Integer status=data.getStatus();
                            if (status.equals(ProjectMirrorEnum.Status._0.code)||status.equals(ProjectMirrorEnum.Status._INIT.code)) {
                                importedStatus =0;
                                importedDesc = "导入中";
                            }else if(status.equals(ProjectMirrorEnum.Status._1.code)){
                                importedStatus =1;
                                importedDesc = "导入成功";
                            }else if (status.equals(ProjectMirrorEnum.Status._7.code)) {
                                importedStatus =7;
                                importedDesc = "导入失败";
                            }else{
                                importedStatus =1;
                                importedDesc = "导入成功";
                            }
                            repo.setImportedDesc(importedDesc);
                            repo.setImportedStatus(importedStatus);
                        }else{
                            StringBuilder targetPath = new StringBuilder(targetNameSpace);
                            targetPath.append("/").append(repo.getName());
                            targetPathList.add(targetPath.toString());
                            repo.setTargetPath(targetPath.toString());
                        }                    }
                }else{
                    for (MirrorRepositoryVO repo : repos){
                        StringBuilder targetPath = new StringBuilder(targetNameSpace);
                        targetPath.append("/").append(repo.getName());
                        targetPathList.add(targetPath.toString());
                        repo.setTargetPath(targetPath.toString());
                    }
                }
                //查询目标仓库是否已存在，防止已存在仓库path被导入，存在的仓库path,importedStatus=-2
                //Set<String> existRepoPath=projectFeignClient.isExistBatch(ProjectIsExistDTO.builder().pathList(targetPathList).build());
                Set<String> existRepoPath=null;
                if(existRepoPath!=null&&existRepoPath.size()>0){
                    repos.parallelStream().filter(repo->repo.getImportedStatus()==-1).forEach(repo->{
                        if(existRepoPath.contains(repo.getTargetPath())){
                            repo.setImportedStatus(-2);
                        }
                    });
                }
                int total=repos.size();
                result.setImportCount(importCount);
                if (importCount > 0) {
                    result.setTotalCount(total);
                    result.setNotImportCount(total- importCount);
                }else{
                    result.setTotalCount(total);
                    result.setNotImportCount(total);
                }
            }
        }
        result.setThirdUserName(thirdUserName);
        result.setToken(userGithubToken.getData());
        return result;
    }

    @Override
    public  List<MirrorNameSpaceVO> getNamespace(MirrorConfigQuery params) throws Exception {
        Integer type=params.getType();
        String userId=params.getCurrUserId();
        //根据查询条件查询用户token信息
        UserGithubToken userGithubToken=userGithubTokenService.getValidToken(userId,type);
        if(userGithubToken==null){
            throw new BusinessException(ResultCodeEnum.MIRROR_GITHUB_TOKEN_INVALID);
        }
        String token=userGithubToken.getData();
        String thirdUserName = userGithubToken.getThirdUsername();
        UserTokenEnum.Type t = UserTokenEnum.Type.parse(type);
        return  SpringBeanUtil.getBean(t.getThirdApiService()).listUserNamespaces(token, thirdUserName);
    }

    @Override
    public Integer changeMirrorSyncStatus(MirrorSyncStatusDTO params) throws Exception{
        Long id=params.getId();
        String token=params.getToken();
        ProjectMirrorData projectMirrorData=baseMapper.selectById(id);
        if(projectMirrorData==null){
            return 0;
        }
        Integer sync=params.getIsSync();
        //更新镜像仓库的同步开关
        LambdaUpdateWrapper<ProjectMirrorData> updateWrapper = new UpdateWrapper<ProjectMirrorData>().lambda();
        updateWrapper.eq(ProjectMirrorData::getId, params.getId());
        updateWrapper.set(ProjectMirrorData::getIsSync, sync);
        if(StringUtils.isNotBlank(token)){
            updateWrapper.set(ProjectMirrorData::getToken, token);
        }
        if (projectMirrorData.getProjectId()!=null) {
            updateWrapper.set(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._1.code);
            updateWrapper.set(ProjectMirrorData::getSyncStatus, ProjectMirrorEnum.Status._1.code);
        } else {
            updateWrapper.set(ProjectMirrorData::getStatus, ProjectMirrorEnum.Status._0.code);
            updateWrapper.set(ProjectMirrorData::getSyncStatus, ProjectMirrorEnum.Status._0.code);
        }
        int result=baseMapper.update(null,updateWrapper);
        //开启的时候，需要加入队列,立即进行同步或者导入
        if(result>0&&sync==1){
            importMirrorService.push(id);
        }
        return result;
    }

    @Override
    public void importProjectRetry(ImportRetryDTO params) {
        Long id=params.getId();
        String targetPath=params.getTargetPath();
        String currUserId=params.getCurrUserId();
        if(StringUtils.isBlank(currUserId)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"currUserId");
        }
        ProjectMirrorData projectMirrorData=baseMapper.selectById(id);
        if(projectMirrorData==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        String fullPath=projectMirrorData.getFullPath();
        //updateWrapper.set(ProjectMirrorData::getStatus, 7);
        LambdaUpdateWrapper<ProjectMirrorData> updateWrapper = new UpdateWrapper<ProjectMirrorData>().lambda();
        updateWrapper.eq(ProjectMirrorData::getId, id);
        if(!targetPath.equals(fullPath)){
            //判断命名空间下项目是否存在
         /*   ProjectVo projectVo=null;
            try {
                //projectVo=projectFeignClient.getProjectDetailByPath(targetPath);
                projectVo=null;
            }catch (Exception e){
                log.info("query projetct error:{}",e.getMessage());
            }
            if(projectVo!=null){
                throw new BusinessException(ResultCodeEnum.IMPORT_RETRY_ERROR);
            }*/
            //证明命名空间改变，需要更新相关镜像信息重新导入
            String path=targetPath.substring(0,targetPath.lastIndexOf("/"));
            //String pathId=nameSpaceFeignClient.pathToTargetId(path);
            String pathId="";
            if(StringUtils.isBlank(pathId)){
                throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"targetPath");
            }
            updateWrapper.set(ProjectMirrorData::getStatus, -1);
            updateWrapper.set(ProjectMirrorData::getFullPath, targetPath);
            updateWrapper.set(ProjectMirrorData::getCreatorId, currUserId);
            updateWrapper.set(ProjectMirrorData::getTargetOrg, path);
            updateWrapper.set(ProjectMirrorData::getTargetOrgId, pathId);
            updateWrapper.set(ProjectMirrorData::getProjectId, null);
            updateWrapper.set(ProjectMirrorData::getLastError, null);
            updateWrapper.set(ProjectMirrorData::getLastExecutionAt, null);
            updateWrapper.set(ProjectMirrorData::getNextExecutionAt, null);
            baseMapper.update(null,updateWrapper);
        }else{
            updateWrapper.set(ProjectMirrorData::getStatus, 0);
        }
        //开启的时候，需要加入队列,立即进行同步或者导入
        importMirrorService.push(id);
    }
}